package com.weiaibenpao.demo.chislim.base;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyf.barlibrary.ImmersionBar;
import com.squareup.leakcanary.RefWatcher;
import com.weiaibenpao.demo.chislim.MyApplication;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by wlx on 2017/12/4.
 */

public abstract class BaseFragment<V extends BaseView,T extends BasePresenter<V>> extends Fragment {
    public T mPresenter;
    public View mView;
    private Unbinder unbinder;
    private boolean isImmersionBarEnabled=false;
    protected ImmersionBar mImmersionBar;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            mView=inflater.inflate(getLayoutId(),container,false);
        if (isImmersionBarEnabled){
            initImmersionBar();
        }
        unbinder=ButterKnife.bind(this,mView);
        mPresenter=initPresenter();
        if (mPresenter!=null)mPresenter.attack((V) this);
        init(savedInstanceState);
        return mView;

    }




    /**
     * 初始化沉浸式状态栏
     */
    private void initImmersionBar() {
        mImmersionBar=ImmersionBar.with(this).statusBarDarkFont(true);
        mImmersionBar.keyboardEnable(true). //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                navigationBarWithKitkatEnable(false);//是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
    }

    /**
     * 布局
     * @return
     */
    @LayoutRes
    public abstract int getLayoutId();

    protected abstract void init(Bundle savedInstanceState);
    protected  T initPresenter(){
        return null;
    };
    /**
     * 是否在Fragment使用沉浸式
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return isImmersionBarEnabled;
    }
    public void setImmersionBarEnabled(boolean isImmersionBarEnabled) {
        this.isImmersionBarEnabled= isImmersionBarEnabled;
    }

    /**
     * 以show()和hide()方式控制Fragment显示隐藏，别忘了重写onHiddenChanged方法
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden&&mImmersionBar!= null){
            mImmersionBar.init();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mImmersionBar!=null){
            mImmersionBar.destroy();
        }
        if (mPresenter!=null)mPresenter.detach();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
